//打包 npm run pack-builder
var app = new Vue({
    el: '#app',
    data: {
        isLoading: false,
        title: '精彩推荐',
        screen:'***',
        currentNav: -1,
        navs: [{
            key: 'meishi',
            label: '美食'
        },{
            key: 'xiaoqingxin',
            label: '小清新'
        },{
            key: 'zhiwu',
            label: '植物'
        },{
            key: 'youxi',
            label: '游戏'
        },{
            key: 'shuaige',
            label: '帅哥'
        },{
            key: 'qiche',
            label: '汽车'
        },{
            key: 'tiyu',
            label: '体育'
        },{
            key: 'junshi',
            label: '军事'
        },{
            key: 'jiaju',
            label: '家具'
        },{
            key: 'fengjing',
            label: '风景'
        },{
            key: 'wmyjdmbz',
            label: '动漫'
        },{
            key: 'wallpaper_0_0_0_1',
            label: '其他'
        },{
            key: 'query',
            label: '搜索'
        }],
        list: [],
        currentPage: 1,
        pages: [],
        alert:{
            show:false,
            title:'',
            content:''
        },
        dialog:{
            show:false,
            autoLogin:false,
            isCircle:false,
            interval:5 //单位：分钟
        },
        isSetCircle:false,
        preview:false,
        showCondition: false,
        condition:{
            class:{
                first:0,
                second:0,
                third:0
            },
            title:{
                first:'全部',
                second:'全部',
                third:'全部'
            },
            url:''
        },
        showError:false
    },
    created: function (){
        this.getScreen()
        // this.setTitle();
        // this.fill();
    },
    mounted: function(){
        console.log('加载完成..');
        this.show('diannaozhuomian')
        this.circleWallpaper();
    },
    methods: {
        goMain:function(){
            this.setTitle(null,'精彩推荐');
            this.show('diannaozhuomian')
            this.circleWallpaper();
        },
        getScreen: function (){
            var height = window.screen.height;
            var width = window.screen.width;
            var screen = width + '*' + height;
            this.screen = screen;
        },
        setTitle: function(key,title) {
            $this = this;
            if(key){
                this.navs.forEach(item => {
                    if (item.key == key){
                        $this.title = item.label + (key == 'query' ? '':'桌面壁纸');
                        return false;
                    }
                });
            }else{
                $this.title = title;
            }
            
        },
        fill: function(){
            for (const i in 15) {
                this.list.append({
                    img_url: 'placeholder.jpg',
                    set_btn_label: '设置壁纸'
                });
            }
        },
        show: function(key){
            this.showCondition = false;
            this.condition.url = '';
            this.currentPage = 1;
            this.currentNav = key;
            this.setTitle(key);
            this.loadData(key);
        },
        loadData: function (key){
            this.fill();
            this.showCondition = false;
            this.showError = false;
            this.isLoading = true;
            this.list = [];
            this.pages = [];
            console.log('当前抓取页数：' + this.currentPage)
            var href = 'http://www.win4000.com/zt/{0}{1}.html';
            if(this.condition.url != ''){
                var url = this.condition.url;
                url = url.replace('{0}', this.currentPage);
                href = url;
                console.log(url);
            }else{
                if(key == 'wallpaper_0_0_0_1'){
                    href = 'http://www.win4000.com/wallpaper_0_0_0_{0}.html';
                    href = href.replace('{0}', this.currentPage);
                }else{
                    href = href.replace('{0}',key);
                    if(Number(this.currentPage) > 1){
                        href = href.replace('{1}','_' + this.currentPage);
                    }else{
                        href = href.replace('{1}','');
                    }
                }
            }
            
            superagent.get(href).end((error,response)=>{
                this.isLoading = false;
                //获取页面文档数据
                var content = response.text;
                if(content == null || content == ''){
                    return ;
                }
                //cheerio也就是nodejs下的jQuery  将整个文档包装成一个集合，定义一个变量$接收
                var $ = cheerio.load(content);

                if($(".error").length>0){
                    this.showCondition = false;
                    this.showError = true;
                    return ;
                }
                //定义一个空数组，用来接收数据
                var tab_tj = $(".Left_bar div.tab_tj").get(0);
                //抓取内容
                $(tab_tj).find("ul li").each((index,el)=>{
                    if(index < 15){
                        //var img_url = $(el).find("a").children("img").attr("data-original");
                        var img_url = $(el).find("a").children("img").attr("data-src");
                        console.log(img_url)
                        this.list.push({img_url:img_url,set_btn_label: '设置壁纸',preview_btn_label:'预览'})
                    }
                });
                console.log(this.list)
                //抓取分页栏
                var hasNextPage = false;
                $(".Left_bar div.pages div").children().each((index,el)=>{
                    var page = $(el).text();
                    console.log(page);
                    this.pages.push(page);
                });
                console.log(this.pages);
            });
            this.currentNav = key;
        },
        showByPage: function(currentPage){
            this.currentPage = Number(currentPage);
            this.loadData(this.currentNav);
        },
        showByPrevPage: function(currentPage){
            this.currentPage = Number(currentPage) - 1;
            this.loadData(this.currentNav);
        },
        showByNextPage: function(currentPage){
            this.currentPage = Number(currentPage) + 1;
            this.loadData(this.currentNav);
        },
        setWallpaper: function(url,index){
            this.list[index].set_btn_label = '切换中...';
            var dl_url = url.replace('_270_185','');
            console.log(url);
            $this = this;
            this.download(dl_url, function(res){
                console.log(res);
                console.log('下载成功');
                /**
                 * 
                 * cmd.get(
                    'call wallpaper.exe',
                    function(err, data, stderr){
                        if (!err) {
                            console.log('the node-cmd cloned dir contains these files :\n\n',data)
                            $this.list[index].set_btn_label = '设置壁纸';
                        } else {
                            console.log('error', err)
                        }
                    }
                );
                 */
                exec('call wallpaper.exe', function(err,stdout,stderr){
                    if(err) {
                        console.log('call wallpaper.exe error:'+stderr);
                    } else {
                        $this.list[index].set_btn_label = '设置壁纸';
                        console.log('壁纸设置成功.');
                        localStorage.setItem("current_cache",url);
                        // console.log(os.homedir());
                        // console.log(os.platform());
                        // var rootDir = os.homedir() + '\\AppData\\Roaming\\Microsoft\\Windows\\Themes';
                        // $this.copyIt('./btf_wallpaper_20200322.jpg',rootDir + '\\TranscodedWallpaper.jpg');
                        var exePath = process.cwd()
                        console.log('exePath:' + exePath);
                        exec('REG ADD "HKEY_CURRENT_USER\\Control Panel\\Desktop" /v "WallPaper" /d "'+exePath+'\\btf_wallpaper_20200322.jpg" /f',{ encoding: 'gbk' },function(err,stdout,stderr){
                            console.log( iconv.decode(stdout, 'cp936'));
                            if(err) {
                                console.log('注册表 error:'+iconv.decode(stderr, 'cp936'));
                            } else {
                                console.log('注册表成功');
                            }
                        })
                    }
                });    
            });
        },
        copyIt:function(from ,to ){
            try {
                fs.readFile(from, function(err, data) {
                    if (err) {
                        console.log("读取失败");
                    } else {
                        fs.writeFile(to,data,function(error){
                            if(error){
                                throw error;
                            }else{
                                console.log("文件已保存");    
                            }
                        });
                    }
                }); 
            } catch (error) {
                console.log(error);
            }
        },
        copyItSync:function(from ,to ){
            try {
                fs.writeFileSync(to, fs.readFileSync(from));    
            } catch (error) {
                console.log(error);
                
            }
        },
        previewWallpaper: function(url,index){
            // this.showAlert('提示','看看就得啦，要啥自行车...');
            var that = this;
            if(this.preview){
                return ;
            }

            fs.exists("./btf_wallpaper_20200322.jpg", function(exists){ 
                if(!exists){ 
                    that.showAlert('提示', '请先设置壁纸后再进行预览！');
                    return ;
                }else{
                    that.doPreviewWallpaper(url,index);
                }
            });
            
            
        },
        doPreviewWallpaper:function(url,index){
            var that = this;
            this.preview = true;
            this.list[index].preview_btn_label = '下载中...';
            var dl_url = url.replace('_270_185','');
            console.log(url);
            var time = 30;//单位：秒
            var interval = null;
            this.downloadAndCopy(dl_url, function(res){
                console.log(res);
                console.log('预览下载成功');
                exec('call wallpaper.exe', function(err,stdout,stderr){
                    if(err) {
                        console.log('call wallpaper.exe error:'+stderr);
                        that.preview = false;
                    } else {
                        console.log('壁纸预览成功.');
                        interval = setInterval(function(){
                            if(time <= 0){
                                console.log('时间到清除定时器start');
                                that.restore(index);
                                console.log('时间到清除定时器end');
                                clearInterval(interval);
                            }
                            that.list[index].preview_btn_label = '正在预览...' + time + 's';
                            time--;
                            
                        },1000);
                        
                    }
                });    
            });
        },
        restore:function(index){
            var that = this;
            fs.exists("./btf_wallpaper_20200322.jpg.bak", function(exists){ 
                if(exists){ 
                    fs.rename("./btf_wallpaper_20200322.jpg.bak","./btf_wallpaper_20200322.jpg",function(err){ 
                        if(err){ 
                            console.log("还原重命名失败！"); 
                        }else{ 
                            console.log("还原重命名成功！"); 
                            exec('call wallpaper.exe', function(err,stdout,stderr){
                                if(err) {
                                    console.log('call wallpaper.exe error:'+stderr);
                                } else {
                                    console.log('还原壁纸成功.');
                                    that.preview = false;
                                    that.list[index].preview_btn_label = '预览';
                                }
                            });   
                        } 
                    });
                }else{ 
                    console.log("还原文件不存在") 
                } 
            });
        },
        download: function(img_src, callback){
            request.head(img_src,function(err,res,body){
                if(err){
                    console.log(err);
                }
                callback(res);
            });
            var img_filename = 'btf_wallpaper_20200322.jpg';  
            request(img_src).pipe(fs.createWriteStream('./'+ img_filename));  
        },
        downloadAndCopy: function(img_src, callback){
            var that = this;
            fs.exists("./btf_wallpaper_20200322.jpg", function(exists){ 
                if(exists){ 
                    fs.rename("./btf_wallpaper_20200322.jpg","./btf_wallpaper_20200322.jpg.bak",function(err){ 
                        if(err){ 
                            console.log("重命名失败！"); 
                        }else{ 
                            console.log("重命名成功！"); 
                            that.download(img_src, callback);
                        } 
                    });
                }else{ 
                    console.log("文件不存在") 
                    that.download(img_src, callback);
                } 
            });
            
        },
        min:function(){
            console.log('call:min');
            ipcRenderer.send('min');
        },
        max:function(){
            console.log('call:max');
            ipcRenderer.send('max');
        },
        close:function(){
            console.log('call:close');
            ipcRenderer.send('close');
        },
        autoLogin:function(){
            console.log('call:auto');
            ipcRenderer.send('auto',!this.dialog.autoLogin);
        },
        defaultSet:function(){
            if(this.dialog.interval <= 0){
                this.dialog.interval = 5;
            }
        },
        set:function(){
            console.log('设置:');
            console.log(this.dialog.isCircle)
            var json = {"isCircle":this.dialog.isCircle,"interval":this.dialog.interval,"autoLogin":this.dialog.autoLogin};
            localStorage.setItem("set_cache",JSON.stringify(json));
            this.closeDialog();
            this.circleWallpaper();
            this.autoLogin();
        },
        circleWallpaper:function(){
            var i = 0;
            var interval = 5;
            if(this.isSetCircle){
                clearInterval(this.isSetCircle);
                i = 0;
            }
            var that = this;
            var value = localStorage.getItem("set_cache");
            if(value){
                var json = JSON.parse(value);
                if(!json.isCircle){
                    return;
                }
                interval = Number(json.interval);
            }
            this.isSetCircle = setInterval(function(){
                var len = that.list.length;
                if(i >= len){
                    i = 0;
                }
                
                var url = that.list[i].img_url;
                var value = localStorage.getItem("current_cache");
                if(value && value == url){
                    i++;
                }
                var dl_url = url.replace('_270_185','');
                that.download(dl_url, function(res){
                    console.log('轮询切换：下载成功');
                    exec('call wallpaper.exe', function(err,stdout,stderr){
                        if(err) {
                            console.log('轮询切换：call wallpaper.exe error:'+stderr);
                        } else {
                            console.log('轮询切换：壁纸设置成功.');
                            localStorage.setItem("current_cache",url);
                        }
                    });    
                });
                i++; 
            },interval*1000*60);
        },
        showSet:function(){
            console.log('打开设置....');
            this.showDialog();
        },
        showAlert:function(title,message){
            this.alert.title = title;
            this.alert.content = message;
            this.alert.show = true;
        },
        closeAlert:function(){
            this.alert.show = false;
        },
        showDialog:function(){
            var value = localStorage.getItem("set_cache");
            if(value){
                var json = JSON.parse(value);
                this.dialog.isCircle = json.isCircle
                this.dialog.interval = json.interval;
                this.dialog.autoLogin = json.autoLogin;
            }
            this.dialog.show = true;
        },
        closeDialog:function(){
            this.dialog.show = false;
        },
        goQuery:function(){
            this.showCondition = true;
            console.log(this.showCondition)
        },
        query:function(q1,q2,q3,q4,e){
            var title = this.condition.title;
            if (q1 != null){
                this.condition.class.first = q1;
                title.first = e.target.innerHTML;
            }else if (q2 != null){
                this.condition.class.second = q2;
                title.second = e.target.getAttribute('title');
            }else if (q3 != null){
                this.condition.class.third = q3;
                title.third = e.target.innerHTML;
            }else if (q4 != null){
            }
            var url = 'http://www.win4000.com/wallpaper_'
            +this.condition.class.first+'_'
            +this.condition.class.second+'_'
            +this.condition.class.third+'_{0}.html';
            this.condition.url = url;
            this.showCondition = false;
            this.currentPage = 1;
            
            this.condition.title = title;
            this.setTitle(null,'搜索：' + this.condition.title.first + '&' + this.condition.title.third + '&' + this.condition.title.second);
            this.loadData(null);
            
        }
    }
})